#include "eventthread.h"

using std::bind;

EventThread::EventThread()
:   loop_(NULL),
    exiting_(false),
    thread_(bind(&EventThread::threadFunc, this), "EventThread"),
    mutex_(),
    cond_(mutex_)
{ }

EventThread::~EventThread()
{
    exiting_ = true;
    if (loop_ != NULL)
    {
        loop_->quit();
        thread_.join();
    }
}

EventLoop* EventThread::startLoop()
{
    assert(!thread_.started());
    thread_.start();
    {
        MutexLockGuard lock(mutex_);
        // 一直等到threadFun在Thread里真正跑起来
        while (loop_ == NULL)
            cond_.wait();
    }
    return loop_;
}

void EventThread::threadFunc()
{
    EventLoop loop;

    {
        MutexLockGuard lock(mutex_);
        loop_ = &loop;
        cond_.notify();
    }

    loop.loop();
    //assert(exiting_);
    loop_ = NULL;
}
